<template>
    <div class="p-2">
      <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
        <div class="search" v-show="showSearch">
          <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
            <el-form-item label="材料名字" prop="materialName">
              <el-input v-model="queryParams.materialName" placeholder="请输入材料名字" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </transition>
  
      <el-card shadow="never">
        <template #header>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['sj:cakeMaterial:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
        </template>
        <el-table
          v-loading="loading"
          :data="cakeMaterialList"
          row-key="id"
          :default-expand-all="isExpandAll"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          ref="cakeMaterialTableRef">
          <!--        <el-table-column label="父id" align="center" prop="parentId" />-->
          <el-table-column label="材料名字" align="left" prop="materialName" />
          <!-- <el-table-column label="材料剩余" align="center" prop="materialSurplus" />
          <el-table-column label="材料价格" align="center" prop="materialPrice" /> -->
          <el-table-column label="材料图片" align="center" prop="materialFileId" width="100">
            <!--          <template #default="scope">-->
            <!--            <image-preview :src="scope.row.materialFileId" :width="50" :height="50"/>-->
            <!--          </template>-->
            <!--          <el-icon><View /></el-icon>-->
            <template #default="scope">
              <el-tooltip content="预览图片" placement="top">
                <el-button :disabled="!scope.row.materialFileId" @click="checkImg(scope.row.materialFileId)" link type="primary" icon="Picture" />
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="创建者名字" align="center" prop="createByName" />
          <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="更新者名字" align="center" prop="updateByName" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['sj:cakeMaterial:edit']" />
              </el-tooltip>
              <el-tooltip content="新增" placement="top">
                <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['sj:cakeMaterial:add']" />
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['sj:cakeMaterial:remove']" />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 添加或修改蛋糕基础材质对话框 -->
      <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
        <el-form ref="cakeMaterialFormRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="上级类别" prop="parentId">
            <el-tree-select
              v-model="form.parentId"
              :data="cakeMaterialOptions"
              :props="{ value: 'id', label: 'materialName', children: 'children' }"
              value-key="id"
              placeholder="请选择上级类别"
              check-strictly
            />
          </el-form-item>
          <el-form-item label="材料名字" prop="materialName">
            <el-input v-model="form.materialName" placeholder="请输入材料名字" />
          </el-form-item>
          <!-- <el-form-item label="材料剩余" prop="materialSurplus">
            <el-input v-model="form.materialSurplus" placeholder="请输入材料剩余" />
          </el-form-item>
          <el-form-item label="材料价格" prop="materialPrice">
            <el-input v-model="form.materialPrice" placeholder="请输入材料价格" />
          </el-form-item> -->
          <el-form-item label="价格区间">
            <el-row>
              <el-col v-for="section in form.workmanshipInfoBos" :key="section.styleId" :span="24">
                <el-form-item :label="section.label" label-width="93px" :style="{marginBottom:'10px'}">
                  <el-input placeholder="请输入价格" v-model.float="section.value"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
          </el-form-item>
          <el-form-item label="材料图片" prop="materialFileId">
            <image-upload v-model="form.materialFileId" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
      <el-image-viewer
        infinite
        :hide-on-click-modal="true"
        @close="closeImageViewer"
        :url-list="(imgList as string[])"
        :initial-index="0"
        v-if="showImageViewer"
      ></el-image-viewer>
    </div>
    
  </template>
  
  <script setup name="CakeMaterial" lang="ts">
  import { listCakeMaterial, getCakeMaterial, delCakeMaterial, addCakeMaterial, updateCakeMaterial } from "@/api/sj/cakeMaterial";
  import { listCakeMaterial as getPriceSectionApi } from '@/api/sj/order';
  import { CakeMaterialVO, CakeMaterialQuery, CakeMaterialForm, PriceSectionType } from '@/api/sj/cakeMaterial/types';
  import { listByIds } from '@/api/system/oss';
  
  type CakeMaterialOption = {
    id: number;
    materialName: string;
    children?: CakeMaterialOption[];
  }
  
  const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  
  
  const cakeMaterialList = ref<CakeMaterialVO[]>([]);
  const cakeMaterialOptions = ref<CakeMaterialOption[]>([]);
  const buttonLoading = ref(false);
  const showSearch = ref(true);
  const isExpandAll = ref(true);
  const loading = ref(false);
  const queryFormRef = ref<ElFormInstance>();
  const cakeMaterialFormRef = ref<ElFormInstance>();
  const cakeMaterialTableRef = ref<ElTableInstance>();
  const showImageViewer = ref(false);
  const imgList = ref<string[]>([]);
  const priceSection = ref<PriceSectionType[]>([]);
  
  
  const dialog = reactive<DialogOption>({
      visible: false,
      title: ''
  });
  
  const dateRangeUpdateTime = ref<[DateModelType, DateModelType]>(['', '']);
  
  const initFormData: CakeMaterialForm = {
      id: undefined,
      parentId: undefined,
      materialName: undefined,
      materialSurplus: undefined,
      materialPrice: undefined,
      materialFileId: undefined,
      workmanshipInfoBos:[]
  }
  
  const data = reactive<PageData<CakeMaterialForm, CakeMaterialQuery>>({
    form: {...initFormData},
    queryParams: {
      materialName: undefined,
      params: {
      }
    },
    rules: {
      id: [
        { required: true, message: "主键不能为空", trigger: "blur" }
      ],
      parentId: [
        { required: true, message: "父id不能为空", trigger: "blur" }
      ],
      materialName: [
        { required: true, message: "材料名字不能为空", trigger: "blur" }
      ],
    }
  });
  
  const { queryParams, form, rules } = toRefs(data);
  
  /** 查询蛋糕基础材质列表 */
  const getList = async () => {
    loading.value = true;
    queryParams.value.params = {};
    proxy?.addDateRange(queryParams.value, dateRangeUpdateTime.value, 'UpdateTime');
    const res = await listCakeMaterial(queryParams.value);
    const data = proxy?.handleTree<CakeMaterialVO>(res.data, "id", "parentId");
    if (data) {
      cakeMaterialList.value = data;
      loading.value = false;
    }
  }
  const checkImg = async (materialFileId:string)=>{
    console.log(materialFileId);
    if(materialFileId){
      await listByIds(materialFileId).then((res)=>{
        console.log(res);
        imgList.value = [res.data[0].url];
        showImageViewer.value = true;
      });
    }else{
      showImageViewer.value = false;
      ElMessage.error('未上传图片');
    }
  };

  /** 获取材料价格区间 */
  const getPriceSection = async ()=>{
    const { data } = await getPriceSectionApi({type:'quantity_enum'});
    priceSection.value = data;
    let priceSectionForm = data.map((item: any,index:number)=>{
      return {
        priceId: item.id,
        label: item.lable,
        profit: item.profit,
        value: undefined,
        sort: index+1,
        styleId:form.value.id||undefined
      }
    });
    form.value.workmanshipInfoBos = [...priceSectionForm];
  };
  
  const closeImageViewer = ()=>{
    showImageViewer.value = false;
  }
  
  /** 查询蛋糕基础材质下拉树结构 */
  const getTreeselect = async () => {
    const res = await listCakeMaterial();
    cakeMaterialOptions.value = [];
    const data: CakeMaterialOption = { id: 0, materialName: '顶级节点', children: [] };
    data.children = proxy?.handleTree<CakeMaterialOption>(res.data, "id", "parentId");
    cakeMaterialOptions.value.push(data);
  }
  
  // 取消按钮
  const cancel = () => {
    reset();
    dialog.visible = false;
  }
  
  // 表单重置
  const reset = () => {
    form.value = {...initFormData}
    cakeMaterialFormRef.value?.resetFields();
  }
  
  /** 搜索按钮操作 */
  const handleQuery = () => {
    getList();
  }
  
  /** 重置按钮操作 */
  const resetQuery = () => {
    dateRangeUpdateTime.value = ['', ''];
    queryFormRef.value?.resetFields();
    handleQuery();
  }
  
  /** 新增按钮操作 */
  const handleAdd = async (row?: CakeMaterialVO) => {
    reset();
    getTreeselect();
    getPriceSection();
    if (row != null && row.id) {
        form.value.parentId = row.id;
    } else {
        form.value.parentId = 0;
    }
    dialog.visible = true;
    dialog.title = "添加蛋糕基础材质";
  }
  
  /** 展开/折叠操作 */
  const handleToggleExpandAll = () => {
    isExpandAll.value = !isExpandAll.value;
    toggleExpandAll(cakeMaterialList.value, isExpandAll.value)
  }
  
  /** 展开/折叠操作 */
  const toggleExpandAll = (data: CakeMaterialVO[], status: boolean) => {
    data.forEach((item) => {
      cakeMaterialTableRef.value?.toggleRowExpansion(item, status)
      if (item.children && item.children.length > 0) toggleExpandAll(item.children, status)
    })
  }
  
  /** 修改按钮操作 */
  const handleUpdate = async (row: CakeMaterialVO) => {
    reset();
    await getTreeselect();
    getPriceSection();
    if (row != null) {
      form.value.parentId = row.id;
    }
    const res = await getCakeMaterial(row.id);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改蛋糕基础材质";
    console.log(res);

    if(res.data?.tworkmanshipInfoVos?.length){
      const twworkmanshipInfo = res.data.tworkmanshipInfoVos.map((item)=>{
        return {
          priceId: item.priceId,
          label: item.label,
          sort: item.sort,
          styleId: item.styleId,
          value: item.value
        }
      });
      form.value.workmanshipInfoBos = [...twworkmanshipInfo];
    }
  }

  /** 提交按钮 */
  const submitForm = () => {
    cakeMaterialFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (form.value.id) {
          await updateCakeMaterial(form.value).finally(() => buttonLoading.value = false);
        } else {
          await addCakeMaterial(form.value).finally(() => buttonLoading.value = false);
        }
        proxy?.$modal.msgSuccess("操作成功");
        dialog.visible = false;
        getList();
      }
    });
  }

  /** 找到被删除的材料的子节点 */
  const findChildren = (node: CakeMaterialVO) => {
    let nodeList:CakeMaterialVO[] = [];
    if(node.children?.length){
      node.children.forEach((item)=>{
        nodeList.push(item);
        nodeList = [...nodeList,...findChildren(item)];
      });
    };
    return nodeList;
  };
  
  /** 删除按钮操作 */
  const handleDelete = async (row: CakeMaterialVO) => {
    const nodeList = findChildren(row);
    nodeList.unshift(row);
    await proxy?.$modal.confirm('是否确认删除蛋糕基础材质名称为"' + row.materialName + '"的数据项？');
    loading.value = true;
    Promise.all(nodeList.map((item)=> delCakeMaterial(item.id))).finally(() => {
      getList()
      loading.value = false;
    });
    proxy?.$modal.msgSuccess("删除成功");
  //   await delCakeMaterial(row.id).finally(() => loading.value = false);
  //   await getList();
  //   proxy?.$modal.msgSuccess("删除成功");
  }
  
  onMounted(() => {
    getList();
  });
  </script>
  